package com.kifas.service.dataaccess;

import java.util.List;

import org.apache.log4j.Logger;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.kifas.entity.PembelianDetailEntity;
import com.kifas.entity.PembelianEntity;

/**
 * @author brainmaster
 * 
 */
@Repository
public class PembelianDao {

	@SuppressWarnings("unused")
	private static Logger log = Logger.getLogger(PembelianDao.class);

	private static String ALL_PEMBELIAN = "From PembelianEntity p ";
	private static String ALL_PEMBELIAN_DETAIL = "from PembelianDetailEntity pd ";
	private static String PEMBELIAN_AND_DETAIL = ALL_PEMBELIAN
			+ "left join fetch PembelianDetailEntity pd ";
	private static String PEMBELIAN_BY_ID = ALL_PEMBELIAN
			+ "where p.idPembelian = :idPembelian ";
	private static String PEMBELIAN_OPEN_STATUS = PEMBELIAN_AND_DETAIL
			+ "where pd.closed = false ";
	private static String PEMBELIAN_CLOSED_STATUS = PEMBELIAN_AND_DETAIL
			+ "where pd.closed = true ";
	private static String PEMBELIAN_DETAIL_BY_PARENT = ALL_PEMBELIAN_DETAIL
			+ "where pd.pembelian = :pembelian ";

	@Autowired
	private SessionFactory sessionFactory;

	public void insert(PembelianEntity pembelian) throws Exception {
		sessionFactory.getCurrentSession().save(pembelian);
		for (PembelianDetailEntity pembelianDetail : pembelian.getPembelianDetails()) {
			sessionFactory.getCurrentSession().save(pembelianDetail);
		}
	}

	@SuppressWarnings("unchecked")
	public List<PembelianEntity> getPembelians() {
		return sessionFactory.getCurrentSession().createQuery(ALL_PEMBELIAN)
				.list();
	}

	public PembelianEntity getPembelianById(Long idPembelian) {
		return (PembelianEntity) sessionFactory.getCurrentSession()
				.createQuery(PEMBELIAN_BY_ID)
				.setLong("idPembelian", idPembelian).uniqueResult();
	}

	@SuppressWarnings("unchecked")
	public List<PembelianEntity> getOpenPembelian() {
		return sessionFactory.getCurrentSession()
				.createQuery(PEMBELIAN_OPEN_STATUS).list();
	}

	@SuppressWarnings("unchecked")
	public List<PembelianEntity> getClosedPembelian() {
		return sessionFactory.getCurrentSession()
				.createQuery(PEMBELIAN_CLOSED_STATUS).list();
	}

	public void updateClosedFlag(Long idPembelian) {
		PembelianEntity pembelian = getPembelianById(idPembelian);
		pembelian.setClosed(true);
		sessionFactory.getCurrentSession().update(pembelian);
	}

	@SuppressWarnings("unchecked")
	public List<PembelianDetailEntity> getPembelianDetails(
			PembelianEntity pembelian) {
		return sessionFactory.getCurrentSession()
				.createQuery(PEMBELIAN_DETAIL_BY_PARENT)
				.setEntity("pembelian", pembelian).list();
	}
}
